//
//  HomeViewController.swift
//  photoBrowser
//
//  Created by herooeoe1 on 16/4/27.
//  Copyright © 2016年 DavidJun. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class HomeViewController: UICollectionViewController {
//MARK: 懒加载属性
    private lazy var shops : [Shop] = [Shop]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

      loadData(0)
       
    }

    
}
//MARK: 发送网络请求
extension HomeViewController
{
    private func loadData(offSet : Int)
    {
         NetworkTools.shareinstance.loadHomeData(offSet) { (result, error) -> () in
//            错误校验
            if error != nil
            {
                print(error)
                return
            }
            
//            获取结果
            guard let resultArray = result else
            {
                print("获取的结果不正确")
                return
            }
            
//            遍历的结果
            for resultDict in resultArray
            {
                let shop = Shop(dict: resultDict)
                self.shops.append(shop)
            }
            
            self.collectionView?.reloadData()
        }
        
    }
}

//MARK: 自定义的函数
extension HomeViewController
{
    private func showPhotoBrowser(indexPath : NSIndexPath)
    {
        //创建图片浏览器的控制器
        let photoBrowserVC = PhotoBrowserViewController()
        //弹出图片浏览器
        presentViewController(photoBrowserVC, animated: true, completion: nil)
    }
}

//MARK: collectionview的数据源和代理方法
extension HomeViewController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.shops.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
//        创建cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("HomeCell", forIndexPath: indexPath) as! HomeCell
//        给cell设置数据
        
       cell.shop = shops[indexPath.item]
        
       if indexPath.item == self.shops.count - 1
       {
          loadData(self.shops.count)
        }
        
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
//        print("\(indexPath.item)")
        showPhotoBrowser(indexPath)
    }
    
}
















